#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <cstdlib>
#include <string>
#include "Log.hpp"
#include "Common.hpp"


using namespace LogModule;


int main(int argc , char* argv[])
{
    if(argc != 3 )
    {
        std::cout<<"Clinet need two arguments"<<std::endl;
        return 1;
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    if(sockfd < 0)
    {
        LOG(LogLevel::ERROR) << "create scokfd false";
    }
    struct sockaddr_in peer;
    memset(&peer,0,sizeof(peer));
    peer.sin_family = AF_INET;
    peer.sin_port = ::htons(port);
    peer.sin_addr.s_addr = ::inet_addr(ip.c_str());
    //inet_pton(AF_INET,ip.c_str(),&server.sin_addr)


    //客户端不用bind 绑定 ，tcp是面向连接的，connect 会自动绑定
    int n = ::connect(sockfd,CONV(&peer),sizeof(peer));
    if(n<0)
    {
        LOG(LogLevel::ERROR)<<"connect false";
        return  1;
    }
    std::string message;
    while(true)
    {
        std::cout<<"Please enter"<<std::endl;
        getline(std::cin,message);
        char inbuffer[1024];
         n = ::write(sockfd, message.c_str(), message.size());
        if(n > 0)
        {
            int m = ::read(sockfd, inbuffer, sizeof(inbuffer));
            if(m > 0)
            {
                inbuffer[m] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
                break;
        }
        else 
            break;
    }
    ::close(sockfd);

    return 0;
}